package cn.edu.zjut.medlinebackend.controller;

import cn.edu.zjut.medlinebackend.enums.MessageTypeEnum;
import cn.edu.zjut.medlinebackend.model.Group;
import cn.edu.zjut.medlinebackend.model.Message;
import cn.edu.zjut.medlinebackend.model.MessageRecordDo;
import cn.edu.zjut.medlinebackend.model.User;
import cn.edu.zjut.medlinebackend.service.MessageService;
import cn.edu.zjut.medlinebackend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 发送消息控制器
 */
@RestController
public class MessageController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SUBSCRIBE_MESSAGE_URI = "/topic/chat/message"; //订阅接收消息地址

    @Resource
    private SimpMessagingTemplate messagingTemplate;
    @Resource
    private UserService userService;

    @Resource
    private MessageService messageService;

    @SubscribeMapping("/chat/participants")
    public Integer getActiveUserNumber(){
        return 1;
    }

    /**
     * 接收并且转发消息
     *
     * @param message
     */
    @MessageMapping("/chat/message")
    public void receiveMessage(Message message) {
        message.setSendDate(new Date());
        message.setMessageType("text");
        logger.info(message.getSendDate() + "," + message.getUserName() + " send a message:" + message.getContent());
        // 保存聊天信息
        User userByName = userService.searchUser(message.getUserName());
        MessageRecordDo messageRecordDo = MessageRecordDo.messageRecordBuilder()
                .groupId(message.getGroupId())
                .userId(userByName == null ? null : userByName.getId())
                .userName(message.getUserName()).content(message.getContent())
                .messageType(MessageTypeEnum.TEXT.getCode()).createTime(new Date()).build();
        userService.addUserMessageRecord(messageRecordDo);
        messagingTemplate.convertAndSend(SUBSCRIBE_MESSAGE_URI, message);
    }

    @RequestMapping("/chat/history/{groupId}")
    public List<MessageRecordDo> historyMessage(@PathVariable Integer groupId){
        List<MessageRecordDo> groups= messageService.getAllMessage(groupId);
        return groups;
    }
}
